import path from 'path'
import glob from 'glob'
import ora from 'ora'
import fs from 'fs-extra'
import 'colors'

let spinner
module.exports = (componentName) => {
  spinner = ora('正初始化组件-'+componentName).start();
  if (isHaveComponent(componentName) && isNeedInitComponent(componentName)) {
    const templateDir = path.resolve(__dirname, `../../templates/components`, componentName)
    fs.copy(templateDir, path.join('./src/components', componentName), function (err) {
      if (err) {
        spinner.fail(`组件初始化失败`.red);
        return console.error(err) 
      } else {
        return spinner.succeed(`组件初始化完成`.green);
      }
    }) //拷贝目录
  } else {
    return
  }
}

function isHaveComponent(componentName) {
  let mmm = false
  const templateDir = path.resolve(__dirname, `../../templates/components`)
  // 获取模版目录文件
  const temFiles = glob.sync(`${templateDir}/*`)
  temFiles.forEach(p => {
    if (path.basename(p) === componentName) {
      mmm = true
    }
  })
  if (!mmm) {
    spinner.fail(`未找到组件-${componentName}`.red)
  }
  return mmm
}

/**
 * 检测当前组件是否需要进行初始化
 * @param {string} projectDir 开发项目工作根目录
 * @returns 是否需要初始化
 */
 function isNeedInitComponent(componentName) {
  let mmm = true
  const sourceFiles = glob.sync(`./src/components/*`)
  sourceFiles.forEach(p => {
    if (path.basename(p) === componentName) {
      spinner.fail(`组件-${componentName}-已经存在，请修改项目名`.red)
      mmm = false
    }
  })
  return mmm
}